<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/jquery-1.8.0.min.js"></script>
</head>

<body>
    <div>
        <span>压缩到</span>
        <input id="size" type="text" value="500">
        <span>kb（默认500kb）</span>
    </div>
    <div style="margin-top: 10px;margin-bottom: 10px;"><input type="file" name="" id="file"></div>
    <img style="width: 420px;" src="" id="img">
    <p><a id="downLoad" href="" download="" target="_blank" rel="noopener noreferrer">下载图片</a></p>
</body>

</html>
<script>
    /* 压缩base64图片，怎么压缩base64是题外话，这里不赘述 */
    function compress(
        base64,        // 源图片
        rate,          // 缩放比例
        callback       // 回调
    ) {
        //处理缩放，转格式
        var _img = new Image();
        _img.src = base64;
        _img.onload = function () {
            var _canvas = document.createElement("canvas");
            var w = this.width / rate;
            var h = this.height / rate;
            _canvas.setAttribute("width", w);
            _canvas.setAttribute("height", h);
            _canvas.getContext("2d").drawImage(this, 0, 0, w, h);
            var base64 = _canvas.toDataURL("image/jpeg");
            _canvas.toBlob(function (blob) {
                let setSize = $("#size").val();
                setSize = setSize ? setSize : 500;
                if (blob.size > Number(setSize) * 1024) {        //如果还大，继续压缩
                    compress(base64, rate, callback);
                } else {
                    callback(base64);
                }
            }, "image/jpeg");
        }
    }
    let fileInput = document.getElementById('file');
    fileInput.addEventListener('change', function () {
        let file = document.querySelector('#file').files[0];

        convertImageToBase64(file).then(function (base64Code) {
            // 获取到 Base64 编码的图片
            compress(base64Code, 1,
                function (base64) {
                    document.getElementById("img").src = base64;
                    $("#downLoad").attr("href", base64);
                    // let link = document.getElementById("downLoad");
                    // link.click();
                }
            )
        }).catch(function (error) {
            // 转化失败
        });
    });

    function convertImageToBase64(file) {
        return new Promise((resolve, reject) => {
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                let image = new Image();
                image.src = e.target.result;

                image.onload = function () {
                    let canvas = document.createElement('canvas');
                    let ctx = canvas.getContext('2d');
                    canvas.width = image.width;
                    canvas.height = image.height;
                    ctx.drawImage(image, 0, 0, image.width, image.height);
                    let base64Code = canvas.toDataURL('image/jpeg');
                    resolve(base64Code);
                };
            };
        });
    }
    //base64数据转Blob文件流对象
    function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(","),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {
            type: mime
        });
    }
</script>